require "abstract_provider.rb"
require "sms_exceptions.rb"

Dir.open(File.dirname(__FILE__) + "/providers/").each do |file|
  if file.match('.rb$')
    require 'providers/' + file
  end
end

class SmsSender

  @main
  @provider

  def initialize(main)
    @main = main
    load_provider()
  end
     
  def debug_send(login, password, to, text)
    SmsWidget::Main.logger.debug "Debug\nlogin = #{login}\npassword = #{password}\nto = #{to}\ntext = #{text}\n"
    sms_sent()
  end

  def sms_sent()
     @main.sms_sent()
  end

  def sms_not_sent(reason)
     @main.sms_not_sent(reason)
  end

  def get_main()
    @main
  end

  def load_provider()
    provider = @main.provider
    provider_list = @main.provider_list_yaml
    SmsWidget::Main.logger.info "Loading provider #{provider}"
    
    unless provider.eql? ""
      class_name = provider_list[provider]["class"]
      @provider = eval("Provider::" + class_name).new(self)
    else
      SmsWidget::Main.logger.warn "sms_sender: no provider loaded!"
    end
    
  end

  def send(to, text)
    begin
      @provider.send(to, text)
      @main.sms_sent()
    rescue InvalidPasswordOrUsernameException
      @main.sms_not_sent("Wrong password or user name.")
    rescue InvalidRecipientNumberException
      @main.sms_not_sent("Wrong recipient number.")
    rescue MessageHasNoCharactersException
      @main.sms_not_sent("Message has no characters.")
    rescue UnknownSmsException
      @main.sms_not_sent("Unknown reason.")
    rescue TooManySmsSentException
      @main.sms_not_sent("You already sent too much SMS.")
    end
  end

end
